/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * CadCliente.java
 *
 * Created on 13/06/2010, 13:43:49
 */
package camada.apresentacao.dialog.cliente;

//import Relatorios.Cliente.ReportCliente;
import eloma.classe.Cliente;
import camada.bancodedados.daoimplemente.cliente.ClienteDAOImpl;
import camada.bancodedados.daoimplemente.JuridicaDAOImpl;
import tabelamodelcolumnmodel.cliente.ClienteColumnModel;
import tabelamodelcolumnmodel.cliente.ClienteTableModel;
import java.awt.Color;
import java.awt.event.KeyEvent;
import java.util.List;
import java.util.logging.Level;
import javax.swing.ListSelectionModel;
import org.jdesktop.swingx.error.ErrorInfo;
import utilitarios.Exceptions;
import utilitarios.erros.MessagemErro;

/**
 *
 * @author Icaro
 */
public class DialogCliente extends javax.swing.JDialog {

    JuridicaDAOImpl daoJuridica = new JuridicaDAOImpl();
    ClienteDAOImpl daoCliente = new ClienteDAOImpl();
    Exceptions exceptions = new Exceptions();

    List<Cliente> listaCliente;
    private String nomeCliente;
    Cliente cliente;
    int indexTabela;
    boolean pesquisa = false;

    /** Creates new form CadCliente */
    public DialogCliente(java.awt.Frame parent, boolean modal) {
        
        super(parent, modal);

        initComponents();
        this.setResizable(false);
        this.setLocationRelativeTo(null);
        this.setTitle("Clientes");
        configurarTabela(null);
        
    }

    public void configurarTabela(List<Cliente> lista) {
        try {

            tabelaCliente.setAutoscrolls(true);
            
            if (lista == null) {
                listaCliente = daoCliente.buscaTodos();
            } else {
                listaCliente = lista;
            }

            //this.setListaCliente(listaCliente);
            tabelaCliente.setModel(new ClienteTableModel(listaCliente));
            
            
            tabelaCliente.setAutoCreateColumnsFromModel(false);
            java.awt.FontMetrics fm = tabelaCliente.getFontMetrics(tabelaCliente.getFont());

            
            //Aki tem um exemplo de como colocar a MyCenderSelll.
            tabelaCliente.setColumnModel(new ClienteColumnModel(fm));
            tabelaCliente.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        } catch (Exception e) {
              MessagemErro erro = new MessagemErro(new ErrorInfo("Erro no Sistema", "Não é Possível Continuar, Sistema Inativo", null, "Fatal", e, Level.WARNING, null),1);
        }
    }

    public void setListaCliente(java.util.List<Cliente> listCliente) {
        this.tabelaCliente.setModel(new ClienteTableModel(listCliente));
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPopupMenu1 = new javax.swing.JPopupMenu();
        jScrollPane1 = new javax.swing.JScrollPane();
        tabelaCliente = new javax.swing.JTable();
        btVoltar = new javax.swing.JButton();
        btAdicionar = new javax.swing.JButton();
        btEditar = new javax.swing.JButton();
        btRemover = new javax.swing.JButton();
        btCancelar = new javax.swing.JButton();
        txPesquisa = new javax.swing.JTextField();
        btPesquisa = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();
        btRelatorio = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        tabelaCliente.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        tabelaCliente.setToolTipText("Tabela de Clientes Cadastrados");
        tabelaCliente.setAutoscrolls(false);
        tabelaCliente.setSelectionBackground(new java.awt.Color(255, 255, 0));
        tabelaCliente.setSelectionForeground(new java.awt.Color(0, 0, 0));
        tabelaCliente.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tabelaClienteMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tabelaCliente);

        btVoltar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ima/cadastro/Voltar.png"))); // NOI18N
        btVoltar.setText("Voltar");
        btVoltar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btVoltarActionPerformed(evt);
            }
        });

        btAdicionar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ima/cadastro/Add.png"))); // NOI18N
        btAdicionar.setText("Adicionar");
        btAdicionar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btAdicionarActionPerformed(evt);
            }
        });

        btEditar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ima/cadastro/Editar.png"))); // NOI18N
        btEditar.setText("Editar");
        btEditar.setEnabled(false);
        btEditar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btEditarActionPerformed(evt);
            }
        });

        btRemover.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ima/cadastro/Remove.png"))); // NOI18N
        btRemover.setText("Remover");
        btRemover.setEnabled(false);
        btRemover.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btRemoverActionPerformed(evt);
            }
        });

        btCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ima/cadastro/Cancel.png"))); // NOI18N
        btCancelar.setText("Cancelar");
        btCancelar.setEnabled(false);
        btCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btCancelarActionPerformed(evt);
            }
        });

        txPesquisa.setForeground(new java.awt.Color(153, 153, 153));
        txPesquisa.setText("Digite um nome para ser pesquisado");
        txPesquisa.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                txPesquisaMouseClicked(evt);
            }
        });
        txPesquisa.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txPesquisaFocusLost(evt);
            }
        });
        txPesquisa.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txPesquisaKeyPressed(evt);
            }
        });

        btPesquisa.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ima/outros/Pesquisa.png"))); // NOI18N
        btPesquisa.setText("Pesquisar");
        btPesquisa.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btPesquisaActionPerformed(evt);
            }
        });

        btRelatorio.setText("Imprimir lista cliente");
        btRelatorio.setEnabled(false);
        btRelatorio.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btRelatorioActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 638, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(btAdicionar, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btEditar)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btRemover)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btCancelar)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btVoltar)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btRelatorio))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(txPesquisa, javax.swing.GroupLayout.PREFERRED_SIZE, 329, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btPesquisa))
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 628, Short.MAX_VALUE))
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btAdicionar)
                    .addComponent(btEditar)
                    .addComponent(btRemover)
                    .addComponent(btCancelar)
                    .addComponent(btVoltar)
                    .addComponent(btRelatorio))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txPesquisa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btPesquisa))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 262, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void tabelaClienteMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tabelaClienteMouseClicked
        try {

            if (evt.getClickCount() == 2) {

                ClienteTableModel model = (ClienteTableModel)tabelaCliente.getModel();
                Cliente cliente = model.getValoresCliente(indexTabela);
                DialogDadosCliente dadosCliente = new DialogDadosCliente(null, true);
                dadosCliente.abastecerCampos(cliente);
                dadosCliente.setVisible(true);
                
                
            } else {

                indexTabela = tabelaCliente.getSelectedRow();

                if (indexTabela > -1) {

                    btAdicionar.setEnabled(false);
                    btVoltar.setEnabled(false);
                    btEditar.setEnabled(true);
                    btRemover.setEnabled(true);
                    btCancelar.setEnabled(true);
                }
            }

        } catch (Exception e) {
             MessagemErro erro = new MessagemErro(new ErrorInfo("Erro no Sistema", "Não é Possível Continuar, Sistema Inativo", null, "Fatal", e, Level.WARNING, null),1);
        }
    }//GEN-LAST:event_tabelaClienteMouseClicked

    private void textDataNascimentoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_textDataNascimentoKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            //textCpf.requestFocus();
        }
    }//GEN-LAST:event_textDataNascimentoKeyPressed

    private void btVoltarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btVoltarActionPerformed
        this.hide();
    }//GEN-LAST:event_btVoltarActionPerformed

    private void btRemoverActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btRemoverActionPerformed
        try{

            ClienteTableModel model = (ClienteTableModel)tabelaCliente.getModel();
            Cliente cliente = model.getValoresCliente(indexTabela);

            daoCliente.remover(cliente);
            
            configurarTabela(null);
            
            btAdicionar.setEnabled(true);
            btCancelar.setEnabled(false);
            btEditar.setEnabled(false);
            btRemover.setEnabled(false);
            btVoltar.setEnabled(true);
            
        }catch(Exception e){
             MessagemErro erro = new MessagemErro(new ErrorInfo("Erro no Sistema", "Não é Possível Continuar, Sistema Inativo", null, "Fatal", e, Level.WARNING, null),1);
        }
    }//GEN-LAST:event_btRemoverActionPerformed

    private void btAdicionarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btAdicionarActionPerformed
        DialogCadCliente cadCliente = new DialogCadCliente(null, true);
        cadCliente.show();
        configurarTabela(null);
    }//GEN-LAST:event_btAdicionarActionPerformed

    private void txPesquisaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txPesquisaMouseClicked
        if (pesquisa == false) {
            txPesquisa.setText("");
            txPesquisa.setForeground(Color.BLACK);
            pesquisa = true;
        }
    }//GEN-LAST:event_txPesquisaMouseClicked

    private void txPesquisaFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txPesquisaFocusLost
        if(txPesquisa.getText() == null ? "" == null : txPesquisa.getText().equals("")){
            txPesquisa.setForeground(new Color(153,153,153));
            txPesquisa.setText("Digite um nome para ser pesquisado");
            pesquisa = false;
        }
    }//GEN-LAST:event_txPesquisaFocusLost

    private void btPesquisaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btPesquisaActionPerformed
        try {

            if((txPesquisa.getText().equals("Digite um nome para ser pesquisado"))||(txPesquisa.getText().equals(null))) {
            
                 List<Cliente> lista = daoCliente.buscaTodos();

                configurarTabela(lista);
                
            }else {
                
                 List<Cliente> listaAux = daoCliente.buscaClienteLikeNome(txPesquisa.getText());

            if (listaCliente.size() > 0) {

                for (int j = 0; j < listaCliente.size(); j++) {
                    
                    Cliente c = (Cliente) listaCliente.get(j);

                    if (c.getNome().equals(txPesquisa.getText())) {
                        listaAux.add(c);
                    }
                }

                configurarTabela(listaAux);
                
            }else{

                List<Cliente> lista = daoCliente.buscaTodos();

                configurarTabela(lista);
            }
                
            }
            
        } catch (Exception e) {
            MessagemErro erro = new MessagemErro(new ErrorInfo("Erro no Sistema", "Não é Possível Continuar, Sistema Inativo", null, "Fatal", e, Level.WARNING, null),1);
        }
    }//GEN-LAST:event_btPesquisaActionPerformed

    private void btRelatorioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btRelatorioActionPerformed
        try {
            List<Cliente> listCl = daoCliente.buscaTodos();

            //ReportCliente reportCli = new ReportCliente(listCl, "teste");
            //reportCli.exibirRelatorio();

        } catch (Exception e) {
            MessagemErro erro = new MessagemErro(new ErrorInfo("Erro no Sistema", "Não é Possível Continuar, Sistema Inativo", null, "Fatal", e, Level.WARNING, null),1);
        }       

    }//GEN-LAST:event_btRelatorioActionPerformed

    private void txPesquisaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txPesquisaKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
           btPesquisaActionPerformed(null);
        }
    }//GEN-LAST:event_txPesquisaKeyPressed

    private void btEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btEditarActionPerformed
        try{
            
            ClienteTableModel model = (ClienteTableModel)tabelaCliente.getModel();
            Cliente cliente = model.getValoresCliente(indexTabela);
            
            DialogCadCliente cadCliente = new DialogCadCliente(null, true);
            cadCliente.carregarEdicao(cliente);
            cadCliente.show();
            configurarTabela(null);
            
        }catch(Exception e){
           MessagemErro erro = new MessagemErro(new ErrorInfo("Erro no Sistema", "Não é Possível Continuar, Sistema Inativo", null, "Fatal", e, Level.WARNING, null),1);
        }
    }//GEN-LAST:event_btEditarActionPerformed

    private void btCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btCancelarActionPerformed
          btAdicionar.setEnabled(true);
            btCancelar.setEnabled(false);
            btEditar.setEnabled(false);
            btRemover.setEnabled(false);
            btVoltar.setEnabled(true);
    }//GEN-LAST:event_btCancelarActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                DialogCliente dialog = new DialogCliente(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btAdicionar;
    private javax.swing.JButton btCancelar;
    private javax.swing.JButton btEditar;
    private javax.swing.JButton btPesquisa;
    private javax.swing.JButton btRelatorio;
    private javax.swing.JButton btRemover;
    private javax.swing.JButton btVoltar;
    private javax.swing.JPopupMenu jPopupMenu1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTable tabelaCliente;
    private javax.swing.JTextField txPesquisa;
    // End of variables declaration//GEN-END:variables
}
